<template>
  <el-dialog :visible="dialogdisbale" @close="close" title="添加">
    <el-form label-width="120px">
      <el-form-item label="章节标题">
        <el-input v-model="chapter.title"></el-input>
      </el-form-item>
      <el-form-item label="章节排序">
        <el-input-number v-model="chapter.sort" :min="0"></el-input-number>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button type="" @click="close">取消</el-button>
      <el-button type="primary" @click="saveandupdate()">确定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import ChatpterApi from "@/api/chapter";
export default {
  data() {
    return {
      dialogdisbale: false,
      chapter: {
        title: "",
        sort: 0,
        chapterId: null,
      },
    };
  },
  methods: {
    open(chapterId) {
      if (chapterId) {
        //编辑状态
        this.chapter.chapterId = chapterId;
        ChatpterApi.getChapterById(chapterId).then((res) => {
          this.chapter = res.data.item;
        });
      }
      this.dialogdisbale = true;
    },
    close() {
      this.dialogdisbale = false;
      this.chapter = { title: "", sort: 0, chapterId: null };//关闭重置状态
    },
    //删除章节
    deleteChapter(id) {
      this.$confirm("删除操作非常危险，确定继续？", "删除提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(() => {
          ChatpterApi.deleteChapterById(id).then((res) => {
            this.$message.success(res.message);
            this.$parent.fetchData(); //重刷
          });
        })
        .catch((error) => {
          if (error == "cancel") {
            this.$message.error("取消删除");
          }
        });
    },
    saveandupdate() {
      //新增状态
      if (this.chapter.chapterId === null) {
        this.chapter.courseId = this.$parent.$parent.courseId;
        ChatpterApi.saveChapter(this.chapter).then((res) => {
          this.$message.success(res.message);
          this.close();
          //刷新列表
          this.$parent.fetchData();
        });
      }
      //更新状态
      else {
        this.chapter.courseId = this.$parent.$parent.courseId;
        ChatpterApi.updateChapter(this.chapter).then((res) => {
          this.$message.success(res.message);
          this.close();
          //刷新列表
          this.$parent.fetchData();
        });
      }
    },
  },
};
</script>
<style scoped>
</style>